package com.spring.sunflower.conversation;

import static com.spring.sunflower.bottompanel.EmotionUtils.EMOTION_CLASSIC_TYPE;

import android.os.Environment;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseMultiItemQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.makeramen.roundedimageview.RoundedImageView;
import com.spring.sunflower.R;
import com.spring.sunflower.base.BaseApplication;
import com.spring.sunflower.bean.MessageCustomEntity;
import com.spring.sunflower.bean.MessageEntity;
import com.spring.sunflower.util.DateTimeUtils;
import com.spring.sunflower.util.DisplayUtils;
import com.tencent.imsdk.v2.V2TIMDownloadCallback;
import com.tencent.imsdk.v2.V2TIMElem;
import com.tencent.imsdk.v2.V2TIMVideoElem;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * Created by Kevin on 2021/6/5<br/>
 * <p>
 * Describe:<br/>
 */
public class ChatCustomSystemAdapter extends BaseMultiItemQuickAdapter<MessageCustomEntity, BaseViewHolder> {
    private static final int AUDIO_MIN_WIDTH = DisplayUtils.dip2px(BaseApplication.getContext(), 60);
    private static final int AUDIO_MAX_WIDTH = DisplayUtils.dip2px(BaseApplication.getContext(), 250);
    private static final int DEFAULT_MAX_SIZE_WIDTH = 400;
    private static final int DEFAULT_MAX_SIZE_HEIGHT = 600;
    private static final int DEFAULT_MAX_SIZE_WIDTH2 = 600;

    public ChatCustomSystemAdapter(@Nullable List<MessageCustomEntity> data) {
        super(data);
        addItemType(MessageCustomEntity.MSG_TYPE_TEXT, R.layout.adapter_conversation_message_text);
        addItemType(MessageCustomEntity.MSG_TYPE_IMAGE, R.layout.adapter_conversation_message_image);
        addItemType(MessageCustomEntity.MSG_TYPE_CUSTOM_GIFT, R.layout.adapter_conversation_message_image);
        addItemType(MessageCustomEntity.MSG_TYPE_AUDIO, R.layout.adapter_conversation_message_audio);
        addItemType(MessageCustomEntity.MSG_TYPE_VIDEO, R.layout.adapter_conversation_message_video);
        addItemType(MessageCustomEntity.MSG_TYPE_CUSTOM, R.layout.adapter_conversation_message_video);
        addItemType(MessageCustomEntity.MSG_TYPE_TIME, R.layout.adapter_conversation_message_time);
    }

//    @Override
//    protected void convert(@NotNull BaseViewHolder holder, CustomMessageBean messageEntity) {
//        switch (holder.getItemViewType()) {
//            case MessageEntity.MSG_TYPE_TEXT:
////                processCommon(holder, messageEntity);
////                holder.setText(R.id.tv_text, messageEntity.getTextElem().getText());
//
//                break;
//            case MessageEntity.MSG_TYPE_IMAGE:
//                boolean self = messageEntity.isSelf();
//                ImageView userIconLeft = holder.getView(R.id.user_icon_left);
//                LinearLayout llContent = holder.getView(R.id.llContent);
//                ImageView userIconRight = holder.getView(R.id.user_icon_right);
//                if (self) {
//                    userIconLeft.setVisibility(View.GONE);
//                    userIconRight.setVisibility(View.VISIBLE);
//                    Glide.with(getContext())
//                            .load(messageEntity.getFaceUrl())
//                            .error(R.drawable.ic_placeholder)
//                            .into(userIconRight);
//                } else {
//                    userIconLeft.setVisibility(View.VISIBLE);
//                    userIconRight.setVisibility(View.GONE);
//                    Glide.with(getContext())
//                            .load(messageEntity.getFaceUrl())
//                            .error(R.drawable.ic_placeholder)
//                            .into(userIconLeft);
//                }
//                RoundedImageView imageView = holder.getView(R.id.image);
//                List<V2TIMImageElem.V2TIMImage> imageList = messageEntity.getImageElem().getImageList();
//                for (V2TIMImageElem.V2TIMImage v2TIMImage : imageList) {
//                    String uuid = v2TIMImage.getUUID(); // 图片 ID
//                    int imageType = v2TIMImage.getType(); // 图片类型
//                    int size = v2TIMImage.getSize(); // 图片大小（字节）
//                    int width = v2TIMImage.getWidth(); // 图片宽度
//                    int height = v2TIMImage.getHeight(); // 图片高度
//                    // 设置图片下载路径 imagePath，这里可以用 uuid 作为标识，避免重复下载
//                    String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
//                    LogUtils.dTag("ChatAdapter", "absolutePath=" + absolutePath);
//                    String imagePath = absolutePath + File.separator + "myUserID" + uuid;
//                    File imageFile = new File(imagePath);
//                    if (imageType == V2TIMImageElem.V2TIM_IMAGE_TYPE_THUMB) {
//                        if (!imageFile.exists()) {
//                            v2TIMImage.downloadImage(imagePath, new V2TIMDownloadCallback() {
//                                @Override
//                                public void onProgress(V2TIMElem.V2ProgressInfo v2ProgressInfo) {
//
//                                }
//
//                                @Override
//                                public void onError(int i, String s) {
//
//                                }
//
//                                @Override
//                                public void onSuccess() {
//                                    Glide.with(getContext())
//                                            .load(imagePath)
//                                            .error(R.drawable.ic_placeholder)
//                                            .into(imageView);
//                                }
//                            });
//                        } else {
//                            Glide.with(getContext())
//                                    .load(imagePath)
//                                    .error(R.drawable.ic_placeholder)
//                                    .into(imageView);
//                        }
//                    }
//                }
//
//                break;
//            case MessageEntity.MSG_TYPE_AUDIO:
//                processCommon(holder, messageEntity);
//                RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
//                        ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
//                params.addRule(RelativeLayout.CENTER_VERTICAL);
//                ImageView audioPlayImage = holder.getView(R.id.iv_audio_play);
//                LinearLayout audioContentView = holder.getView(R.id.llContent);
//                FrameLayout msgContentFrame = holder.getView(R.id.fl_msg_content);
//                TextView audioTimeText = holder.getView(R.id.tv_audio_time);
//                if (messageEntity.isSelf()) {
//                    params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
//                    params.rightMargin = 24;
//                    audioPlayImage.setImageResource(R.drawable.msg_voice_playing_3);
//                    audioPlayImage.setRotation(180f);
//                    audioContentView.removeView(audioPlayImage);
//                    audioContentView.addView(audioPlayImage);
//                } else {
//                    params.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
//                    params.leftMargin = 24;
//                    // TODO 图标不对
//                    audioPlayImage.setImageResource(R.drawable.msg_voice_playing_3);
//                    audioContentView.removeView(audioPlayImage);
//                    audioContentView.addView(audioPlayImage, 0);
////                    if (msg.getCustomInt() == UNREAD) {
////                        LinearLayout.LayoutParams unreadParams = (LinearLayout.LayoutParams) isReadText.getLayoutParams();
////                        unreadParams.gravity = Gravity.CENTER_VERTICAL;
////                        unreadParams.leftMargin = 10;
////                        unreadAudioText.setVisibility(View.VISIBLE);
////                        unreadAudioText.setLayoutParams(unreadParams);
////                    } else {
////                        unreadAudioText.setVisibility(View.GONE);
////                    }
//                }
////                audioContentView.setLayoutParams(params);
//                // 语音消息
//                V2TIMSoundElem v2TIMSoundElem = messageEntity.getSoundElem();
//                // 语音 ID,内部标识，可用于外部缓存 key
//                String uuid = v2TIMSoundElem.getUUID();
//                // 语音文件大小
//                int dataSize = v2TIMSoundElem.getDataSize();
//                // 语音时长
//                int duration = v2TIMSoundElem.getDuration();
//                if (duration == 0) {
//                    duration = 1;
//                }
//                // 设置语音文件路径 soundPath，这里可以用 uuid 作为标识，避免重复下载
//                String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
//                String soundPath = absolutePath + File.separator + "myUserID" + uuid;
//                File soundFile = new File(soundPath);
//                // 判断 soundPath 下有没有已经下载过的语音文件
//                if (!soundFile.exists()) {
//                    v2TIMSoundElem.downloadSound(soundPath, new V2TIMDownloadCallback() {
//                        @Override
//                        public void onProgress(V2TIMElem.V2ProgressInfo progressInfo) {
//                            // 下载进度回调：已下载大小 v2ProgressInfo.getCurrentSize()；总文件大小 v2ProgressInfo.getTotalSize()
//                        }
//
//                        @Override
//                        public void onError(int code, String desc) {
//                            // 下载失败
//                        }
//
//                        @Override
//                        public void onSuccess() {
//                            // 下载完成
//                        }
//                    });
//                } else {
//                    // 文件已存在
//                }
//                ViewGroup.LayoutParams audioParams = msgContentFrame.getLayoutParams();
//                audioParams.width = AUDIO_MIN_WIDTH + DisplayUtils.dip2px(getContext(), duration * 6);
//                if (audioParams.width > AUDIO_MAX_WIDTH) {
//                    audioParams.width = AUDIO_MAX_WIDTH;
//                }
//                msgContentFrame.setLayoutParams(audioParams);
//                audioTimeText.setText(duration + "''");
//                msgContentFrame.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View view) {
//                        if (AudioPlayer.getInstance().isPlaying()) {
//                            AudioPlayer.getInstance().stopPlay();
//                            return;
//                        }
////                        if (TextUtils.isEmpty(msg.getDataPath())) {
////                            ToastUtil.toastLongMessage(TUIKit.getAppContext().getString(R.string.voice_play_tip));
////                            return;
////                        }
//                        audioPlayImage.setImageResource(R.drawable.play_voice_message);
//                        if (messageEntity.isSelf()) {
//                            audioPlayImage.setRotation(180f);
//                        }
//                        final AnimationDrawable animationDrawable = (AnimationDrawable) audioPlayImage.getDrawable();
//                        animationDrawable.start();
////                        msg.setCustomInt(READ);
////                        unreadAudioText.setVisibility(View.GONE);
//                        AudioPlayer.getInstance().startPlay(soundPath, new AudioPlayer.Callback() {
//                            @Override
//                            public void onCompletion(Boolean success) {
//                                audioPlayImage.post(new Runnable() {
//                                    @Override
//                                    public void run() {
//                                        animationDrawable.stop();
//                                        audioPlayImage.setImageResource(R.drawable.msg_voice_playing_3);
//                                        if (messageEntity.isSelf()) {
//                                            audioPlayImage.setRotation(180f);
//                                        }
//                                    }
//                                });
//                            }
//                        });
//                    }
//                });
//                break;
//            case MessageEntity.MSG_TYPE_VIDEO:
//                processVideo(holder, messageEntity);
//                break;
//            default:
//                break;
//        }
//    }

    private void processVideo(@NotNull BaseViewHolder holder, MessageEntity messageEntity) {
        boolean self = messageEntity.isSelf();
        ImageView userIconLeft = holder.getView(R.id.user_icon_left);
        LinearLayout llContentLeft = holder.getView(R.id.llLeftContent);
        LinearLayout llContentRight = holder.getView(R.id.llRightContent);
        ImageView userIconRight = holder.getView(R.id.user_icon_right);
        if (self) {
            userIconLeft.setVisibility(View.GONE);
            userIconRight.setVisibility(View.VISIBLE);
            Glide.with(getContext())
                    .load(messageEntity.getFaceUrl())
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_placeholder)
                    .into(userIconRight);
            llContentLeft.setVisibility(View.GONE);
            llContentRight.setVisibility(View.VISIBLE);
        } else {
            userIconLeft.setVisibility(View.VISIBLE);
            userIconRight.setVisibility(View.GONE);
            Glide.with(getContext())
                    .load(messageEntity.getFaceUrl())
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_placeholder)
                    .into(userIconLeft);
            llContentRight.setVisibility(View.GONE);
            llContentLeft.setVisibility(View.VISIBLE);
        }
        RoundedImageView imageView = holder.getView(R.id.image);
        // 视频消息
        V2TIMVideoElem v2TIMVideoElem = messageEntity.getVideoElem();
        // 视频截图 ID,内部标识，可用于外部缓存 key
        String snapshotUUID = v2TIMVideoElem.getSnapshotUUID();
        // 视频截图文件大小
        int snapshotSize = v2TIMVideoElem.getSnapshotSize();
        // 视频截图宽
        int snapshotWidth = v2TIMVideoElem.getSnapshotWidth();
        // 视频截图高
        int snapshotHeight = v2TIMVideoElem.getSnapshotHeight();
        // 视频 ID,内部标识，可用于外部缓存 key
        String videoUUID = v2TIMVideoElem.getVideoUUID();
        // 视频文件大小
        int videoSize = v2TIMVideoElem.getVideoSize();
        // 视频时长
        int duration = v2TIMVideoElem.getDuration();
        // 设置视频截图文件路径，这里可以用 uuid 作为标识，避免重复下载
        String absolutePath = Environment.getExternalStorageDirectory().getAbsolutePath();
//        String snapshotPath = absolutePath + File.separator + "snapshot/" + "myUserID" + snapshotUUID;
        String snapshotPath = absolutePath + File.separator + "myUserID" + snapshotUUID;
        LogUtils.dTag("ChatAdapter", snapshotPath);
        File snapshotFile = new File(snapshotPath);
        if (!snapshotFile.exists()) {
            v2TIMVideoElem.downloadSnapshot(snapshotPath, new V2TIMDownloadCallback() {
                @Override
                public void onProgress(V2TIMElem.V2ProgressInfo progressInfo) {
                    // 下载进度回调：已下载大小 v2ProgressInfo.getCurrentSize()；总文件大小 v2ProgressInfo.getTotalSize()
                }

                @Override
                public void onError(int code, String desc) {
                    // 下载失败
                    LogUtils.dTag("ChatAdapter", "code=" + code + ",desc=" + desc);
                }

                @Override
                public void onSuccess() {
                    // 下载完成
                    Glide.with(getContext())
                            .load(snapshotPath)
                            .error(R.drawable.ic_placeholder)
                            .into(imageView);
                }
            });
        } else {
            // 文件已存在
            Glide.with(getContext())
                    .load(snapshotPath)
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_placeholder)
                    .into(imageView);
        }

        // 设置视频文件路径，这里可以用 uuid 作为标识，避免重复下载
        String videoPath = absolutePath + File.separator + "video/" + "myUserID" + snapshotUUID;
        File videoFile = new File(videoPath);
//        if (!snapshotFile.exists()) {
//            v2TIMVideoElem.downloadSnapshot(videoPath, new V2TIMDownloadCallback() {
//                @Override
//                public void onProgress(V2TIMElem.V2ProgressInfo progressInfo) {
//                    // 下载进度回调：已下载大小 v2ProgressInfo.getCurrentSize()；总文件大小 v2ProgressInfo.getTotalSize()
//                }
//
//                @Override
//                public void onError(int code, String desc) {
//                    // 下载失败
//                }
//
//                @Override
//                public void onSuccess() {
//                    // 下载完成
//
//                }
//            });
//        } else {
//            // 文件已存在
//        }
    }

    private void processCommon(@NotNull BaseViewHolder holder, MessageCustomEntity messageEntity) {
        boolean self = messageEntity.isSelf();
        com.spring.sunflower.util.LogUtils.INSTANCE.logI("ChatCustom", "isSelf=" + self);
        ImageView userIconLeft = holder.getView(R.id.user_icon_left);
        LinearLayout llContentLeft = holder.getView(R.id.llLeftContent);
        LinearLayout llContentRight = holder.getView(R.id.llRightContent);
        ImageView userIconRight = holder.getView(R.id.user_icon_right);
        if (self) {//自己发送的显示在右侧，发送这的头像
            userIconLeft.setVisibility(View.INVISIBLE);
            userIconRight.setVisibility(View.VISIBLE);
            Glide.with(getContext())
                    .load(messageEntity.getFromUserPhoto())
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_placeholder)
                    .into(userIconRight);
//            com.spring.sunflower.util.LogUtils.INSTANCE.logI("ChatCustom", "self===" + messageEntity.getFromUserPhoto());
            llContentLeft.setVisibility(View.GONE);
            llContentRight.setVisibility(View.VISIBLE);
        } else {
            userIconLeft.setVisibility(View.VISIBLE);
            userIconRight.setVisibility(View.INVISIBLE);
            Glide.with(getContext())
                    .load(R.drawable.ic_system_notice)
                    .placeholder(R.drawable.ic_placeholder)
                    .error(R.drawable.ic_placeholder)
                    .into(userIconLeft);
//            com.spring.sunflower.util.LogUtils.INSTANCE.logI("ChatCustom", "self===" + messageEntity.getToUserPhoto());
            llContentRight.setVisibility(View.GONE);
            llContentLeft.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void convert(@NotNull BaseViewHolder holder, MessageCustomEntity messageCustomEntity) {
        switch (holder.getItemViewType()) {
            case MessageCustomEntity.MSG_TYPE_TEXT:
                processCommon(holder, messageCustomEntity);
//                holder.setText(R.id.tv_text, messageCustomEntity.getContent());
                TextView tvText;
                if (messageCustomEntity.isSelf()) {
                    tvText = holder.getView(R.id.tv_text_right);
                } else {
                    tvText = holder.getView(R.id.tv_text_left);
                }
                tvText.setText(SpanStringUtils.handleEmojiText(EMOTION_CLASSIC_TYPE, getContext(), tvText, messageCustomEntity.getContent()));
//                holder.setText(R.id.tv_text, SpanStringUtils.getEmotionContent(EMOTION_CLASSIC_TYPE, getContext(), tvText, messageCustomEntity.getContent()));
//                holder.setText(R.id.tv_text, SpanStringUtils.handleEmojiText(EMOTION_CLASSIC_TYPE, getContext(), tvText, messageCustomEntity.getContent()));
                break;
            case MessageCustomEntity.MSG_TYPE_CUSTOM_GIFT:
                processCommon(holder, messageCustomEntity);
                if (messageCustomEntity.isSelf()) {
                    RoundedImageView giftRight = holder.getView(R.id.imageRight);
                    Glide.with(getContext())
                            .load(messageCustomEntity.getGiftImagePath())
                            .placeholder(R.drawable.ic_placeholder)
                            .error(R.drawable.ic_icon_placeholder)
                            .into(giftRight);
                    holder.setText(R.id.tvGiftTipRight, "你送给" + messageCustomEntity.toUserNickname + messageCustomEntity.giftName + messageCustomEntity.giftNumber + "个");
                } else {
                    RoundedImageView giftLeft = holder.getView(R.id.imageLeft);
                    Glide.with(getContext())
                            .load(messageCustomEntity.getGiftImagePath())
                            .placeholder(R.drawable.ic_placeholder)
                            .error(R.drawable.ic_icon_placeholder)
                            .into(giftLeft);
                    holder.setText(R.id.tvGiftTipLeft, messageCustomEntity.fromUserNickname + "送给你" + messageCustomEntity.giftName + messageCustomEntity.giftNumber + "个");
                }
                break;
            case MessageCustomEntity.MSG_TYPE_AUDIO:
                processCommon(holder, messageCustomEntity);
                if (messageCustomEntity.isSelf()) {
                    TextView tvAudioTimeRight = holder.getView(R.id.tv_audio_time_right);
                    tvAudioTimeRight.setText(messageCustomEntity.audioDuration + "''");
                } else {
                    TextView tvAudioTimeLeft = holder.getView(R.id.tv_audio_time_left);
                    tvAudioTimeLeft.setText(messageCustomEntity.audioDuration + "''");
                }
                break;
            case MessageCustomEntity.MSG_TYPE_IMAGE:
                processCommon(holder, messageCustomEntity);
                TextView tvRight = holder.getView(R.id.tvGiftTipRight);
                TextView tvLeft = holder.getView(R.id.tvGiftTipRight);
                tvLeft.setVisibility(View.GONE);
                tvRight.setVisibility(View.GONE);
                if (messageCustomEntity.isSelf()) {
                    RoundedImageView imageRight = holder.getView(R.id.imageRight);
                    imageRight.setLayoutParams(getImageParams(imageRight.getLayoutParams(), messageCustomEntity));
                    Glide.with(getContext())
                            .load(messageCustomEntity.getPicUrl())
                            .placeholder(R.drawable.ic_placeholder)
                            .error(R.drawable.ic_icon_placeholder)
                            .into(imageRight);
                } else {
                    RoundedImageView imageLeft = holder.getView(R.id.imageLeft);
                    imageLeft.setLayoutParams(getImageParams(imageLeft.getLayoutParams(), messageCustomEntity));
                    Glide.with(getContext())
                            .load(messageCustomEntity.getPicUrl())
                            .placeholder(R.drawable.ic_placeholder)
                            .error(R.drawable.ic_icon_placeholder)
                            .into(imageLeft);
                }
                break;
            case MessageCustomEntity.MSG_TYPE_TIME:
                long timestamp = messageCustomEntity.getTimestamp();
                holder.setText(R.id.tv_chat_time, DateTimeUtils.getTimeFormatText(new Date(timestamp * 1000)));
                break;
            default:
                processCommon(holder, messageCustomEntity);
                holder.setText(R.id.tv_text, "[不支持的消息]");
                break;

        }
    }

    private ViewGroup.LayoutParams getImageParams(ViewGroup.LayoutParams params, final MessageCustomEntity msg) {
        LogUtils.dTag("ChatCustomAdapter", "hyeight" + msg.getPicHeight() + ",msg.getPicWidth()" + msg.getPicWidth() + ",msgW" + msg.picWidth + ",msgH=" + msg.picHeight + "=");
        if (msg.getPicWidth() == 0 || msg.getPicHeight() == 0) {
            return params;
        }
        if (msg.getPicWidth() / (float) msg.getPicHeight() < 1.2f) {
            params.width = DEFAULT_MAX_SIZE_WIDTH;
            params.height = DEFAULT_MAX_SIZE_WIDTH * msg.getPicHeight() / msg.getPicWidth();
        } else if (msg.getPicWidth() / (float) msg.getPicHeight() >= 1.3f) {
            params.width = DEFAULT_MAX_SIZE_WIDTH2;
            params.height = DEFAULT_MAX_SIZE_WIDTH * msg.getPicHeight() / msg.getPicWidth();
        } else {
            params.width = DEFAULT_MAX_SIZE_HEIGHT * msg.getPicWidth() / msg.getPicHeight();
            params.height = DEFAULT_MAX_SIZE_HEIGHT;
        }
        return params;
    }
}

